<?php

namespace App\Http\Controllers;

use App\Common\Constant\Params;
use App\Events\MerchantOrderComplain;
use App\Events\MerchantOrderRefund;
use App\Events\OrderEmployed;
use App\Events\OrderEvaluated;
use App\Events\OrderSuccess;
use App\Models\Master;
use App\Models\MerchantTradeLog;
use App\Models\Order;
use App\Models\OrderComplain;
use App\Models\OrderDetail;
use App\Models\OrderEvaluate;
use App\Models\OrderGoods;
use App\Models\OrderOffer;
use App\Models\OrderRefund;
use App\Models\OrderStatus;
use App\Services\Factory\PaymentFactory;
use App\Services\IOrderService;
use App\Services\IPayService;
use App\Services\ISystemService;
use App\Services\ISystemTaskService;
use App\Services\IWalletService;
use DB;
use Illuminate\Http\Request;

class MockController extends Controller
{

    /**
     * 模拟添加一个订单
     */
    public function addOrder(Request $request,ISystemService $systemService)
    {
        DB::beginTransaction();

        try{
            $order_number = $systemService->genOrderNumber();
            //订单
            $confirm_code = random(6,'PNUMBER');
            $order = Order::create([
                'order_number'=>$order_number,
                'merchant_id'=>rand(1,100),
                'service_category'=>Params::SERVICE_CATEGORY_FURNITURE,//家具类
                'service_type'=>array_rand(Params::$MERCHANT_SERVICE_TYPE),//提货配送上门
                'confirm_code'=>$confirm_code,
                'push_time'=>time(),
            ]);
            $order_id = $order->id;

            //订单商品
            OrderGoods::create([
                'order_id'=>$order_id,
                'goods_id'=>mt_rand(),
                'goods_type'=>array_rand(Params::$GOODS_CATEGORY),
                'goods_name'=>'货品型号'.random(),
                'goods_mark'=>'货品备注'.random(),
                'goods_num'=>rand(1,10),
                'goods_img'=>'http://on7uwttp2.bkt.clouddn.com/20170322/fnfKsSviQv0Aoss8pvxFat6l9oR9GRZYKgVWgHx7.jpeg',
                'goods_price'=>rand(200,500),
            ]);
            OrderGoods::create([
                'order_id'=>$order_id,
                'goods_id'=>mt_rand(),
                'goods_type'=>array_rand(Params::$GOODS_CATEGORY),
                'goods_name'=>'货品型号'.random(),
                'goods_mark'=>'货品备注'.random(),
                'goods_num'=>rand(1,10),
                'goods_img'=>'/20170326/2sLDDBSkuj9f5kBwwFkDwKWtuSFPyDpHynabXcn6.jpeg',
                'goods_price'=>rand(200,500),
            ]);
            //订单信息详情
            OrderDetail::create([
                'order_id'=>$order_id,
                'customer_name'=>'客户姓名'.$confirm_code,
                'customer_phone'=>'客户手机'.$confirm_code,
                'customer_area_id'=>Master::first()->service_area_ids[array_rand(Master::first()->service_area_ids)],
                'customer_address'=>'详细地址'.$confirm_code,
                'customer_elevator'=>array_rand(Params::$ELEVATOR),
                'customer_floor'=>rand(1,7),
                'customer_tmall_number'=>random(20),
                'customer_memark'=>'备注说明'.$confirm_code,
                'logistics_packages'=>rand(1,3),
                'logistics_ticketnumber'=>random(16),
                'logistics_name'=>['顺丰','申通','韵达'][rand(0,2)],
                'logistics_phone'=>[15051877991,13770846442,15777963320][rand(0,2)],
                'logistics_address'=>'提货地址'.$confirm_code,
                'logistics_consignee'=>'收货人姓名'.$confirm_code,
                'logistics_mark'=>'物流备注'.$confirm_code,
                'merchant_name'=>'下单联系人'.$confirm_code,
                'merchant_phone'=>[15051877991,13770846442,15777963320][rand(0,2)],
                'merchant_finish_time'=>time()+rand(86400*14,86400*30),
            ]);
            //订单状态
            OrderStatus::create([
                'order_id'=>$order_id,
            ]);

            DB::commit();

            return 'order_id: '.$order_id."<br /><a href='".url('mock/all')."'>返回模拟操作订单列表</a>";
        }catch (\Exception $e){
            DB::rollBack();
            throw $e;
        }

    }

    /**
     * 所有订单
     * @param Request $request
     */
    public function all(Request $request,IOrderService $orderService)
    {
        $list = $orderService->all();
        return view('mock/all',['list'=>$list]);
    }

    /**
     * 查看订单
     */
    public function offer(Order $order,Request $request,IOrderService $orderService)
    {
        $orderService->loadOrderAllInfo($order);
        return view('mock/offer',['order'=>$order]);
    }

    /**
     * 模拟支付预付款雇佣师傅
     */
    public function employOrder($order_id, $master_id, Request $request,ISystemService $systemService,IPayService $payService)
    {
        $payer = PaymentFactory::factory(Params::PAY_METHOD_ALIPAY);
        if ($request->has('sign')){
            $ret = $payer->verifyReturn();
            if ($ret){
                event(new OrderEmployed($order_id));
            }
            return ($ret ? 'success' : 'fail')."<br /><a href='".url('mock/all')."'>返回模拟操作订单列表</a>";
        }

        DB::beginTransaction();

        try {
            $offer = OrderOffer::where(['order_id' => $order_id, 'master_id' => $master_id])->first();
            $merchant_price = $offer->price * (1 + config('common.earn_percent_per_order'));
            $order = Order::find($order_id);
            $trade_number = $systemService->genTradeNumber();

            $trade_log = MerchantTradeLog::create([
                'merchant_id'=>$order->merchant_id,
                'merchant_name'=>$order->merchant->me_username,
                'trade_number'=>$trade_number,
                'direction'=>Params::TRADE_DIRECTION_OUT,
                'amount'=>$merchant_price,
                'type'=>Params::MERCHANT_TRADE_TYPE_ORDER,
                'source'=>Params::TRADE_SOURCE_ALIPAY,
                'balance'=>$order->merchant->me_money,
                'order_number_list'=>$order_id,
                'order_serial_number_list'=>$order->order_number,
                'ip'=>getip(),
                'status'=>Params::TRADE_STATUS_SUCCESS,
                'alipay_no'=>'',
            ]);
            if (!$trade_log){
                DB::rollBack();
            }

            $ret = $trade_log;

            $ret = $order->update([
                'master_id' => $master_id,
                'offer_price' => $offer->price,
                'merchant_price' => $merchant_price,
                'appoint_time' => time(),
                'pay_time' => time()
            ]);
            if (!$ret){
                DB::rollBack();
            }
//
            if ($ret){
                DB::commit();
            }else{
                DB::rollBack();
            }
//
//            $ret = $ret && event(new OrderEmployed($order_id));
//
//            return ($ret ? 'success' : 'fail')."<br /><a href='".url('mock/all')."'>返回模拟操作订单列表</a>";
            if (!$ret){
                return 'fail'."<br /><a href='".url('mock/all')."'>返回模拟操作订单列表</a>";
            }
        } catch (\Exception $e) {
            DB::rollBack();
            throw $e;
        }


        return $payer->form($trade_number, $merchant_price, config('app.name')."订单支付",[
            'return_url'=>url()->current(),
            'order_type'=>Params::MERCHANT_TRADE_TYPE_ORDER,
            'pay_method'=>Params::PAY_METHOD_ALIPAY,
            'payer_type'=>Params::USER_TYPE_MERCHANT,
        ]);
    }

    /**
     * 对订单申请退款
     * @param $order_id
     * @param Request $request
     */
    public function refundOrder($order_id,Request $request,ISystemService $systemService)
    {
        DB::beginTransaction();

        try{
            $order = Order::find($order_id);
            $order_number = $systemService->genInsideOrderNumber();
//            $refund = OrderRefund::create([
//                    'order_number'=>$order_number,
//                    'order_id'=>$order_id,
//                    'refund_reason'=>'退款理由'.random(),
//                    'refund_time'=>time(),
//                    'refund_type'=>Params::ORDER_REFUND_FULL,
//                    'refund_amount'=>$order->merchant_pay_money,
//                    'refund_method'=>Params::REFUND_METHOD_ORIGIN,
//                ]);
            $refund = OrderRefund::create([
                    'order_number'=>$order_number,
                    'order_id'=>$order_id,
                    'refund_reason'=>'退款理由'.random(),
                    'refund_time'=>time(),
                    'refund_type'=>Params::ORDER_REFUND_PART,
                    'refund_amount'=>$order->merchant_pay_money*0.8,
                    'refund_method'=>Params::REFUND_METHOD_ORIGIN,
                ]);
            if (!$refund){
                DB::rollBack();
            }
            $ret = $refund && OrderStatus::where('order_id',$order_id)->take(1)->update(['refund_status'=>Params::ORDER_REFUND_REFUNDING]);

            if (!$ret){
                DB::rollBack();
            }

            $ret = $ret && event(new MerchantOrderRefund($refund->id));

            if ($ret){
                DB::commit();
            }else{
                DB::rollBack();
            }

            return ($ret ? 'success' : 'fail')."<br /><a href='".url('mock/all')."'>返回模拟操作订单列表</a>";
        }catch (\Exception $e){
            DB::rollBack();
            throw $e;
        }

    }

    /**
     * 对订单申请仲裁
     * @param $order_id
     * @param Request $request
     */
    public function arbitrateOrder($order_id,Request $request)
    {
        DB::beginTransaction();

        try{
            $refund = OrderRefund::where('order_id',$order_id)->first();
            if (!$refund){
                return 'fail';
            }
            $ret = OrderRefund::where('order_id',$order_id)->update([
                    'arbitrate_time'=>time(),
                    'arbitrate_name'=>'仲裁申请人ooxx',
                    'arbitrate_phone'=>176369094,
                    'arbitrate_reason'=>'申请仲裁原因！',
                    'arbitrate_imgs'=>json_encode(['http://on7uwttp2.bkt.clouddn.com/20170322/fnfKsSviQv0Aoss8pvxFat6l9oR9GRZYKgVWgHx7.jpeg','/20170326/2sLDDBSkuj9f5kBwwFkDwKWtuSFPyDpHynabXcn6.jpeg']),
                ]) && OrderStatus::where('order_id',$order_id)->take(1)->update(['arbitrate_status'=>Params::ORDER_ARBITRATE_ARBITRATING]);

            if ($ret){
                DB::commit();
            }else{
                DB::rollBack();
            }
            return ($ret ? 'success' : 'fail')."<br /><a href='".url('mock/all')."'>返回模拟操作订单列表</a>";
        }catch (\Exception $e){
            DB::rollBack();
            throw $e;
        }

    }

    /**
     * 模拟到账一个订单
     */
    public function transferOrder($order_id,Request $request,ISystemTaskService $systemTaskService,ISystemService $systemService)
    {
        $ret = event(new OrderSuccess($order_id));
        return ($ret ? 'success' : 'fail')."<br /><a href='".url('mock/all')."'>返回模拟操作订单列表</a>";
    }

    /**
     * 评价一个订单
     */
    public function evaluateOrder($order_id,Request $request,ISystemService $systemService)
    {
        DB::beginTransaction();

        try{
            $evaluate = OrderEvaluate::firstOrCreate([
                'oe_orderid'=>$order_id,
            ],[
                'oe_score'=>rand(1,3),
                'oe_quality'=>rand(1,5),
                'oe_attitude'=>rand(1,5),
                'oe_ontime'=>rand(1,5),
                'oe_meid'=>Order::find($order_id)->merchant_id,
                'oe_content'=>'商家对订单的评价'.random(),
            ]);
            $ret = $evaluate && OrderStatus::where('order_id',$order_id)->take(1)->update(['evaluate_status'=>Params::ORDER_EVALUATE_ALREADY]);

            $ret = $ret && event(new OrderEvaluated($evaluate->id));

            if ($ret){
                DB::commit();
            }else{
                DB::rollBack();
            }
            return ($ret ? 'success' : 'fail')."<br /><a href='".url('mock/all')."'>返回模拟操作订单列表</a>";
        }catch (\Exception $e){
            DB::rollBack();
            throw $e;
        }
    }

    /**
     * 投诉一个订单
     */
    public function complainOrder($order_id,Request $request,ISystemService $systemService)
    {
        $order = Order::find($order_id);
        if(!$order){
            return false;
        }
        $complain = OrderComplain::firstOrCreate([
            'oc_orderid'=>$order_id,
        ],[
            'oc_meid'=>$order->merchant_id,
            'oc_category'=>array_rand(Params::$COMPAIN_CATEGORY),
            'oc_subcategory'=>array_rand(Params::$COMPLAIN_SUBCATEGORY),
            'oc_content'=>'投诉内容'.random(6),
            'oc_img'=>['http://on7uwttp2.bkt.clouddn.com/20170322/fnfKsSviQv0Aoss8pvxFat6l9oR9GRZYKgVWgHx7.jpeg','/20170326/2sLDDBSkuj9f5kBwwFkDwKWtuSFPyDpHynabXcn6.jpeg'],
            'oc_number'=>random(12),
        ]);

        $ret = $complain && event(new MerchantOrderComplain($complain->oc_id));

        return ($ret ? 'success' : 'fail')."<br /><a href='".url('mock/all')."'>返回模拟操作订单列表</a>";
    }

}
